from conf import settings
from lib import common
import json
dic = {
    'dusername': None,
    'flag': False
      }
break_s = 0


def pass_name():
    while True:
        name = input("请输入你的用户名(只能含有字母或者数字)：")
        for i in name:
            if name.isdecimal() or 65 <= ord(i) <= 90 or 97 <= ord(i) <= 122:
                break
        else:
            print('用戶名格式錯誤,請重新輸入')
            continue
        return name


def pass_word():
    while True:
        word = input("请输入你的密码(长度要在6~14个字符之间)：")
        if 6 <= len(word) <= 14:
            return word
        else:
            print('密碼格式錯誤')


def login():
    print("欢迎进入注册页面！")
    while True:
        name = pass_name()
        word = pass_word()
        with open(settings.REGISTER_PATH2, 'r', encoding='utf-8')as f:
            for i in f:
                lst = i.strip().split(":")
                if name == lst[0]:
                    print('用户名存在')
                    break
            else:
                with open(settings.REGISTER_PATH2, 'a', encoding='utf-8')as f1:
                    f1.write(f'{name}:{word}:{0}\n')
                return '注册成功'


def enter():
    print("欢迎进入登录页面")
    while True:
        str_login = ""
        break_ls = 1
        break_sd = 1
        name = pass_name()
        word = pass_word()
        with open(settings.REGISTER_PATH2, "r", encoding="utf-8")as f1:
            if name in f1.read():
                with open(settings.REGISTER_PATH2, "r", encoding="utf-8")as f4:
                    for i in f4:
                        lst = i.strip().split(":")
                        if name in i and lst[-1] == '3':
                            print("该用户已被锁定，请联系管理员！")
                            break_sd = 0
                            break
                        if name == lst[0] and word == lst[1]:
                            dic['flag'] = True
                            dic['username'] = name
                            with open(settings.REGISTER_PATH2, "r+", encoding="utf-8")as f5:
                                for j in f5:
                                    if name in j:
                                        lst2 = j.strip().split(":")
                                        sum = int(lst2[-1])
                                        sum = 0
                                        lst2[-1] = str(sum)
                                        str_login += f"{':'.join(lst2)}\n"
                                    else:
                                        str_login += f"{j}"
                                f5.seek(0)
                                f5.write(str_login)
                                return "登录成功"
                    else:
                        print("用户名或者密码错误")
                        with open(settings.REGISTER_PATH2, "r+", encoding="utf-8")as f2:
                            for j in f2:
                                if name in j:
                                    lst2 = j.strip().split(":")
                                    sum = int(lst2[-1])
                                    sum += 1
                                    lst2[-1] = str(sum)
                                    str_login += f"{':'.join(lst2)}\n"
                                else:
                                    str_login += f"{j}"
                            f2.seek(0)
                            f2.write(str_login)
            else:
                print('没有此用户！')
                while True:
                    enter_1 = input("登录其他账号输入C/c，去主页选择注册输入N/n：").replace(" ", "")
                    if enter_1.upper() == 'C':
                        break
                    elif enter_1.upper() == "N":
                        return "已退出登录页面！"
                    else:
                        print("输入错误！")
        if break_sd == 0:
            continue
        with open(settings.REGISTER_PATH2, "r", encoding="utf-8")as f3:
            for n in f3:
                if name in n:
                    lst1 = n.strip().split(":")
                    if int(lst1[-1]) == 3:
                        break_ls = 0
                        break
            if break_ls == 0:
                global break_s
                break_s = 1
                return "该用户已经被锁定，程序立即退出!"


@common.wrapper
def article():
    return f"欢迎进入{dic['username']}的文章页面"


@common.wrapper
def comment():
    print(f"欢迎进入{dic['username']}的评论页面")
    while True:
        count = 0
        with open(settings.REGISTER_PATH1, "r", encoding="utf-8")as f5:
            print("----------------------------------------")
            for l in f5:
                count += 1
                print(f'''{count}楼：{l.replace('"', "")}''')
            print("----------------------------------------")
        comment_x = input("是否评论？（Y or y（评论）/N or n（退出页面））").replace(" ","")
        if comment_x.upper() == "Y":
            s = input("请输入你的评论：")
            with open(settings.REGISTER_PATH1, "a", encoding="utf-8")as f6:
                f6.write(f"\n{dic['username']}:    {json.dumps(s, ensure_ascii=False)}")
        elif comment_x.upper() == "N":
            return "已退出！"
        else:
            print("输入错误！")

@common.wrapper
def diary():
    return f"欢迎进入{dic['username']}的日记页面"


@common.wrapper
def collect():
    return f"欢迎进入{dic['username']}的收藏页面"


@common.wrapper
def logout():
    dic['flag'] = False
    return '--------------已经注销，请重新登录！---------------'


dic_log = {
    '1': login,
    '2': enter,
    '3': article,
    '4': comment,
    '5': diary,
    '6': collect,
    '7': logout,
    '8': quit
}

def run():
    msg = """
    1.请注册
    2.请登录
    3.进入文章页面
    4.进入评论页面
    5.进入日记页面
    6.进入收藏页面
    7.注销账号
    8.退出整个程序
    """
    print(msg)
    while True:
        chose = input('请选择你想进入的功能序号：').replace(" ","")
        if dic['flag'] == True:
            if chose == '1':
                print("已登录成功，无法注册！")
            elif chose == '2':
                print("已登录成功，无法继续登录！")
            elif chose == '3' or chose == '4' or chose == '5' or chose == '6'or chose == '7':
                print(dic_log[chose]())
                if break_s == 1:
                    break
            elif chose == '8':
                print('退出程序')
                break
            else:
                print('输出错误')
        else:
            if chose == '1' or chose == '2' or chose == '3' or chose == '4' or chose == '5' or chose == '6'or chose == '7':
                print(dic_log[chose]())
                if break_s == 1:
                    break
            elif chose == '8':
                print('退出程序')
                break
            else:
                print('输出错误')